package com.base.springboot.starter.nacos.config.autoconfigure.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Configuration 配置类
 *
 * @author admin
 * @date 2020/9/2 下午5:10
 */
@Component
public class NacosConfigClientService {
    @Resource
    private Environment environment;

    @Autowired
    private NacosConfigManager nacosConfigManager;

    /**
     * 获取容器现有 ConfigService
     *
     * @return
     * @throws NacosException
     */
    public ConfigService getConfigService() throws NacosException {
        return nacosConfigManager.getConfigService();
    }

    /**
     * 指定key，获取对应属性值
     *
     * @param key
     * @return
     */
    public String getPropertyByKey(String key) {
        return environment.getProperty(key);
    }

    /**
     * 指定key，获取对应属性值（为空，返回指定默认值）
     *
     * @param key
     * @return
     */
    public String getPropertyByKey(String key, String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }

    /**
     * 指定key，获取对应属性值（指定返回对应类型）
     *
     * @param key
     * @return
     */
    public <T> T getPropertyByKey(String key, Class<T> targetValueType) {
        return environment.getProperty(key, targetValueType);
    }
}
